/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package biz;

import dao.AccountDAO;
import entity.Account;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Young Ran
 */
public class AccountBO {
    
    private String encrypt(String source)
    {
        String out=null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(source.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            out = encoder.encode(digest);
        } catch (NoSuchAlgorithmException ex) {
            System.out.println(ex.getMessage());
        }
        return out;
    }
    //DISPLAY ACCOUNT:
    public ArrayList<Account> getAllAccount() throws SQLException {
        return new AccountDAO().getAllAccount();  
    }
    
    public Account checkPassword(String username,String password) throws SQLException
    {
        ArrayList<Account> arrAccounts = new AccountDAO().getByUName(username);
        if(arrAccounts.size()<1) return null;
        if(encrypt(password).equals((arrAccounts.get(0)).getPassword()))
            return arrAccounts.get(0);
        return null;
    }
    
    public void addAccount(Account item) throws SQLException
    {
        item.setPassword(encrypt(item.getPassword()));
        new AccountDAO().addAccount(item);
    }
    
    public void editAccount(Account item) throws SQLException{
        item.setPassword(encrypt(item.getPassword()));
        new AccountDAO().editAccount(item);
    }
    public void promoteAccount(String username,int level) throws SQLException
    {
        new AccountDAO().promoteAccount(username, level);
    }
}
